import { Application } from 'egg';
import { MEDIUMINT, TEXT, BOOLEAN, Instance, INTEGER } from 'sequelize';

export interface ICommentAttr {
  id?: number;
  articleId: number;
  fromUserId: number;
  toUserId: number;
  replyId?: number;
  content: string;
  main: boolean;
  status?: number;
}

interface ICommentInst extends Instance<ICommentAttr>, ICommentAttr { }

export default (app: Application) => {
  const model = app.model.define<ICommentInst, ICommentAttr>('comment', {
    id: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
    },
    articleId: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
      comment: '文章ID',
    },
    fromUserId: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
      comment: '评论人',
    },
    toUserId: {
      type: MEDIUMINT(8).UNSIGNED,
      comment: '回复人',
    },
    replyId: {
      type: MEDIUMINT(8).UNSIGNED,
      comment: '回复',
    },
    content: {
      type: TEXT,
      allowNull: false,
    },
    main: {     // 主评论
      type: BOOLEAN,
      defaultValue: true,
    },
    status: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 1,    // 0删除
    },
  }, {
    timestamps: true,
    paranoid: false,
    charset: 'utf8mb4',
    // defaultScope: {
    //     where: {
    //         status: 2,
    //     }
    // },
    // scopes: {
    //     deleted: {
    //         where: {
    //             status: 0,
    //         },
    //     },
    // },
  });

  model.associate = () => {
    model.belongsTo(app.model.Article, { foreignKey: 'articleId', as: 'article' });
    model.belongsTo(app.model.User, { foreignKey: 'fromUserId', as: 'from' });
    model.belongsTo(app.model.User, { foreignKey: 'toUserId', as: 'to' });
    model.hasMany(model, { foreignKey: 'replyId', as: 'replys' });

  };
  // model.sync({ alter: true });
  // model.sync({force: true}); //强制
  return model;
};
